package com.zzw.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AccountCondition {

	private final Lock lock = new ReentrantLock();
	private Condition cond = lock.newCondition();
	private String accountNo;
	private double balance;
	private boolean flag = false;
	
	public AccountCondition(){
		
	}
	
	public AccountCondition(String accountNo,double balance){
		this.accountNo = accountNo;
		this.balance = balance;
	}
	
	public void draw(double drawAmount){
		lock.lock();
		try{
			if(!flag){
				cond.await();
			}
			else{
				System.out.println(Thread.currentThread().getName() + 
						"" + drawAmount);
				balance -= drawAmount;
				System.out.println("" + balance);
				flag = false;
				cond.signalAll();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			lock.unlock();
		}
	}
	
	public void deposit(double depositAmount){
		lock.lock();
		try {
			if(flag){
				cond.await();
			}
			else{
				System.out.println(Thread.currentThread().getName() + 
						"" + depositAmount);
				balance += depositAmount;
				System.out.println("" + balance);
				flag = true;
				cond.signalAll();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			lock.unlock();
		}
	}
	
	@Override
	public int hashCode() {
		return accountNo.hashCode();
	}
	
	
	@Override
	public boolean equals(Object obj) {
		if(this == obj){
			return true;
		}
		else if(obj != null && obj.getClass() == Account.class){
			Account target = (Account) obj;
			return target.getAccountNo().equals(accountNo);
		}
		return false;
	}
	
	public String getAccountNo() {
		return accountNo;
	}
	
	public void setAccountNo(String accountNo) {
		this.accountNo = accountNo;
	}

	public double getBalance() {
		return balance;
	}
}